/**
 * 
 */
package com.linkage.im.processor;

import com.alibaba.fastjson.JSONObject;
import org.jim.common.ImAio;
import org.jim.common.ImPacket;
import org.jim.common.http.HttpConst;
import org.jim.common.http.HttpRequest;
import org.jim.common.packets.Command;
import org.jim.common.packets.LoginReqBody;
import org.jim.common.utils.JsonKit;
import org.jim.server.command.CommandManager;
import org.jim.server.command.handler.LoginReqHandler;
import org.tio.core.ChannelContext;

/**
 * @author WChao
 *
 */
public class ClientWsHandshakeProcessor extends org.jim.server.command.handler.processor.handshake.WsHandshakeProcessor {

	@Override
	public void onAfterHandshaked(ImPacket packet, ChannelContext channelContext) throws Exception {
		LoginReqHandler loginHandler = (LoginReqHandler)CommandManager.getCommand(Command.COMMAND_LOGIN_REQ);
		HttpRequest request = (HttpRequest)packet;
		//处理连接入参
		String id = (request.getParams().get("id") == null) ? null : (String)request.getParams().get("id")[0];
		String username = (request.getParams().get("username") == null) ? null : (String)request.getParams().get("username")[0];
		String password = (request.getParams().get("password") == null) ? null : (String)request.getParams().get("password")[0];
		String avatar = (request.getParams().get("avatar") == null) ? null : (String)request.getParams().get("avatar")[0];
		String code = (request.getParams().get("token") == null) ? "0" : (String)request.getParams().get("token")[0];
		String groupName = (request.getParams().get("groupName") == null) ? "临时聊天室" : (String)request.getParams().get("groupName")[0];
		LoginReqBody loginBody = new LoginReqBody(username, password, code);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("code", code);
		jsonObject.put("groupName", groupName);
		jsonObject.put("avatar", avatar);
		jsonObject.put("password", password);
		loginBody.setExtras(jsonObject);
		loginBody.setId(id);
		byte[] loginBytes = JsonKit.toJsonBytes(loginBody);
		request.setBody(loginBytes);
		request.setBodyString(new String(loginBytes,HttpConst.CHARSET_NAME));
		//登录
		ImPacket loginRespPacket = loginHandler.handler(request, channelContext);
		if(loginRespPacket != null){
			ImAio.send(channelContext, loginRespPacket);
		}
	}
}
